<!--  -->
<template>
  <el-dialog v-model="dialogFormVisible" title="假期" width="500" destroy-on-close draggable @closed="handlerClosed">
    <el-form ref="ruleFormRef" :model="form" label-width="100px" :rules="rules">
      <el-form-item label="用户">
        <el-space wrap size="small">
          <el-tag v-for="(item, idx) in userList" size="large" :key="idx" @close="handleCloseTagUser(idx)" effect="plain" closable type="info">
            {{ item.nickName }}
          </el-tag>
        </el-space>
      </el-form-item>
      <el-form-item label="类型" prop="holidayCategory">
        <el-select v-model="form.holidayCategory" placeholder="请选择" size="large">
          <el-option v-for="item in holidayOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="holidayNum">
        <el-input-number v-model="form.holidayNum" :min="0" :max="1000" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startDate">
        <el-date-picker v-model="form.startDate" type="date" format="YYYY-MM-DD" placeholder="选择开始时间" />
      </el-form-item>
      <el-form-item label="结束时间" prop="endDate">
        <el-date-picker v-model="form.endDate" type="date" format="YYYY-MM-DD" placeholder="选择结束时间" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit(ruleFormRef)">提交</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useHolidayCategoryStore } from '../../stores'
import http from '../../http'
import { FormInstance, FormRules } from 'element-plus'
import { formatDate } from '../../utils'

const ruleFormRef = ref<FormInstance>()
const holidayOptions = ref(useHolidayCategoryStore().getAllState() as any)
const dialogFormVisible = ref(false)
const userList = ref<any[]>([])
const form = reactive({
  holidayCategory: 0,
  holidayNum: 0,
  yearNum: 0,
  startDate: '',
  endDate: '',
})

const validateStartDate = (_: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请选择开始日期'))
  } else if (value >= form.endDate) {
    callback(new Error('开始日期必须早于结束日期'))
  } else {
    callback()
  }
}

const validateEndDate = (_: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请选择结束日期'))
  } else if (value <= form.startDate) {
    callback(new Error('结束日期必须晚于开始日期'))
  } else {
    callback()
  }
}
const rules = reactive<FormRules>({
  holidayCategory: [{ required: true, message: '请选择假期类别', trigger: 'change' }],
  holidayNum: [
    { required: true, message: '请输入假期天数', trigger: 'blur' },
    { type: 'number', message: '假期天数必须是数字', trigger: 'blur' },
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' },
    { validator: validateStartDate, trigger: 'change' },
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' },
    { validator: validateEndDate, trigger: 'change' },
  ],
})

const handleCloseTagUser = (idx: number) => {
  userList.value = userList.value.filter((_, index) => index !== idx)
}
/**
 * 打开对话框函数
 *
 * @param item 需要编辑的项目对象
 * @param workTime 工作时间数组，默认为空数组
 */
const openDialog = (_userList: any[], _holidayCategory = 0) => {
  dialogFormVisible.value = true
  userList.value = _userList
  form.holidayCategory = _holidayCategory
  resetForm(ruleFormRef.value)
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const resAll: any[] = []
      userList.value.forEach((item) => {
        form.yearNum = new Date(form.startDate).getFullYear()
        const { userId, userName, userNick, deptId, deptName } = item
        const startDate = formatDate(new Date(form.startDate), 'yyyy-MM-dd')
        const endDate = formatDate(new Date(form.endDate), 'yyyy-MM-dd')
        resAll.push(
          http({
            method: 'POST',
            path: '/dev-api/oa/holiday',
            params: {
              userId,
              userName,
              userNick,
              deptId,
              deptName,
              ...form,
              startDate,
              endDate,
            },
          })
        )
      })
      const res = await Promise.all(resAll)
      console.log('Form is valid, proceed with submission', res)
    } else {
      console.log('Form is valid, proceed with submission')
    }
  })
}

const handlerClosed = () => {
  resetForm(ruleFormRef.value)
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
defineExpose({ openDialog })
</script>
